const express = require('express');
const router = express.Router();
const formidable = require('formidable');
const multiparty = require('multiparty');
const url = require('url');
const session = require('express-session');
const bodyParser = require("body-parser");

router.use(bodyParser.json({
    limit: '10mb'
}))

// 图片上传接口
router.post('/upload', function (req, res) {
    if (req.route.path === '/upload' && req.route.methods.post) {

        var form = new formidable.IncomingForm();
        var dirName = url.parse(req.url, true).query.dir;
        var cName = "uploads/user-info";
        if (dirName) cName = "uploads/" + dirName;
        form.encoding = 'utf-8'; // 编码
        form.keepExtensions = true; // 保留扩展名
        form.maxFieldsSize = 2 * 1024 * 1024; // 文件大小
        form.uploadDir = cName; // 存储路径

        form.parse(req, function (err, fileds, files) { // 解析 formData数据
            if (err) {
                return console.log(err)
            }
            let url = files.file.path;
            url = url.replace(/\\/gi, "/");
            if (files.file) {
                return res.json({
                    code: 200,
                    data: {
                        picInfo: {
                            path: url,
                            size: files.file.size
                        }
                    },
                    msg: '单张图片上传成功'
                })
            }
        })
    }
});

// 多张图片上传接口
router.post('/multiPic', function (req, res) {
    if (req.route.path === '/multiPic' && req.route.methods.post) {

        var form = new multiparty.Form();
        var dirName = url.parse(req.url, true).query.dir;
        var cName = "uploads/user-info";
        if (dirName) cName = "uploads/" + dirName;
        form.encoding = 'utf-8'; // 编码
        form.keepExtensions = true; // 保留扩展名
        form.maxFieldsSize = 2 * 1024 * 1024; // 文件大小
        form.uploadDir = cName; // 存储路径

        form.parse(req, function (err, fields, files) {
            let pathUrl = []
            for (let key in files.files) {
                let url = files.files[key].path;
                url = url.replace(/\\/gi, "/");
                pathUrl.push({
                    path: url,
                    size: files.files[key].size
                })
            }
            return res.json({
                code: 200,
                data: pathUrl,
                msg: '多张图片上传成功'
            })
        });
    }
});

module.exports = router;